<template>
  <div class="modal">
    <!-- 不适用嵌套方式布局,避免后期事件冒泡问的 -->
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 登录box -->
    <div class="loginBox">
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <!-- 导航 -->
      <section class="nav">
        <a href="#" :class="{ active: isShowPhone }" @click="isShowPhone = true"
          >手机号登录</a
        >
        |
        <a href="#" :class="{ active: !isShowPhone }" @click="showQR"
          >微信扫码登录</a
        >
      </section>
      <!-- 内容区域 -->
      <div class="content">
        <!-- 手机登录内容 -->
        <div class="phoneLogin" v-show="isShowPhone">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              class="ipt"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="arr"
              :accuracy="10"
            ></slide-verify>
          </div>
          {{ msg }}
          <div class="row">
            <input
              type="text"
              placeholder="请输入验证码"
              class="ipt"
              v-model="code"
            />
            <!-- <button class="btncode" @click="getCode">
              {{ isShowCount ? count + "s" : "获取验证码" }}
            </button> -->
            <button v-show="!isShowCount" class="btncode" @click="getCode">
              获取验证码
            </button>
            <button v-show="isShowCount" class="btncode">
              {{ count + "s" }}
            </button>
          </div>
          <div class="row">
            <button class="btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 微信扫码内容 -->
        <div class="qrLogin" v-show="!isShowPhone" id="weixin">
          微信扫码登录内容
        </div>
      </div>
    </div>
  </div>
</template>
 
<script>
import { SenSMAPI, PhoneReginAPI, wechatUsersApi } from "@/request/api";
import { mapActions, mapMutations } from "vuex";
import { validatePhoneNuber } from "@/utils/index";
export default {
  data() {
    return {
      msg: "向右滑动",
      arr: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-02.150d92a1.png"),
        require("../assets/img/integral-03.9870f3f1.png"),
        require("../assets/img/integral-04.afadcbdf.png"),
      ],
      isShowPhone: true,
      // 双向绑定
      phoneNumber: "",
      // 倒计时
      count: 59,
      // 显示获取验证码数字or获取验证码字体
      isShowCount: false,
      // 输入验证码
      code: "",
    };
  },
  methods: {
    ...mapMutations({
      // 方法:'模块名称/方法名'
      // 映射登录模块窗口
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      // 映射Login登录后
      changeIsLoinged: "loginStatus/changeIsLoinged",
      // 点击路由时初始化用户信息
      initUserInfo: "userInfo/initUserInfo",
    }),
    ...mapActions({
      asyncchangeIsShowToast: "showToast/asyncchangeIsShowToast",
      asyncUpdateUserInfo: "userInfo/asyncUpdateUserInfo",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    // 封装倒计时
    daojishi() {
      // 倒计时  循环定时器递减数字
      // 显示倒计时
      this.isShowCount = true;
      let timer = setInterval(() => {
        this.count--;
        if (this.count <= 0) {
          this.count = 59;
          // 停止计时器
          clearInterval(timer);
          // 隐藏倒计时
          this.isShowCount = false;
        }
      }, 1000);
    },
    //  封装验证手机号码和拼图滑动
    toVerify() {
      // 1.判断手机号码是否正确,不正确则提示
      // let reg =
      //   /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;

      // reg.test  返回值是true 和 false
      if (!validatePhoneNuber(this.phoneNumber)) {
        // alert("请输入正确的手机号码");
        // 替换成显示Toast组件
        this.asyncchangeIsShowToast({
          isShow: true,
          msg: "请输入正确的手机号码",
          type: "warning",
        });
        return;
      }
      // 2.判断验证码不正确则提示
      // 如果msg等于再试一次 or 向右滑动
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        // alert("请滑动验证码进行校验!");
        this.asyncchangeIsShowToast({
          isShow: true,
          msg: "请滑动验证码进行校验",
          type: "warning",
        });
        return;
      }
      // 如果上面两项都验证成功则返回true,下面调用时就可以继续发送请求逻辑
      return true;
      // 函数默认返回undefined;
    },
    // 获取验证码
    async getCode() {
      let flag = this.toVerify();
      // console.log(flag);
      // 不通过则return 阻止它不往下执行
      if (!flag) return;
      // 3.获取验证码--60s倒计时功能
      // 获取验证码  发请求
      let res = await SenSMAPI({
        phone: this.phoneNumber,
      });
      // console.log("发送短信验证码res:", res);

      if (!res) return;
      this.asyncchangeIsShowToast({
        isShow: true,
        msg: "发送成功",
        type: "success",
      });
      // 调用倒计时方法
      this.daojishi();
    },
    // 登录检验
    async submitFn() {
      // 1.手机号不正确提示
      // 2.拼图滑块不正确提示
      if (!this.toVerify()) return;
      // 3.短信验证码不正确提示
      // 由于目前后台未返回正确的验证码，此处只能做非空校验
      if (this.code.trim() == "") {
        this.asyncchangeIsShowToast({
          isShow: true,
          msg: "请输入验证码",
          type: "danger",
        });
        return;
      }
      // 4.点击登录时分场景,有uuid时,发起手机微信关联请求,否则发起手机登录请求
      let uuid = localStorage.getItem("uuid");
      let res = null; //变量提前
      // 如果有uuid
      if (uuid) {
        res = await wechatUsersApi({
          phone: this.phoneNumber,
          verifyCode: this.code,
          uuid,
        });
        // console.log("微信绑定手机成功res:", res);
      } else {
        // 发起手机登录请求
        res = await PhoneReginAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
        });
      }

      if (!res) return;
      // 1.提示登录成功
      this.asyncchangeIsShowToast({
        isShow: true,
        msg: "登录成功!",
        type: "succes",
      });

      // 2.存储token   obj['a']=obj.a
      localStorage.setItem("x-auth-token", res.data["x-auth-token"]);
      // 3.隐藏登录窗口
      this.changeIsShowLoginModal(false);
      // 4.topbar中登录状态的切换
      this.changeIsLoinged(true);

      // 绑定1.清除code
      if (uuid) {
        this.$router.push(this.$route.path);
      }
      // 绑定1.删除uuid
      localStorage.removeItem("uuid");

      // 获取用户信息并更新Vuex的数据 ---手机登录
      this.asyncUpdateUserInfo();

      /* 
      1.布局一个购物车按钮
      2.vuex中loginStatus存储一个状态isLogined(是否登录的状态)
        store
          loginStatus
            index.js
      3.根据isLogined来控制购物车按钮是否显示
        本地有token isLogined则为true，本地无token则为false
      最终效果，刷新后可以根据本地是否有token来控制是否显示购物车按钮
      */
    },
    // 获取二维码
    showQR() {
      this.isShowPhone = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + this.$route.path)
        ),
        // 调用样式文件
        // 这里是要base64_格式
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5pbmZvew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9ICAgIA0KLmltcG93ZXJCb3ggcXJjb2Rlew0KICAgIG1hcmdpbi10b3A6IDIwcHg7DQp9",
      });
    },
  },
};
</script>
 
<style lang = "less" scoped>
/* scoped只在当前组件有效 */
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
  }
  .loginBox {
    width: 555px;
    height: 423px;
    margin: auto;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background: url("../assets/img/login-box-bg.png");
  }
  .close {
    position: absolute;
    right: 60px;
    top: 18px;
    width: 22px;
    height: 22px;
    background: url("../assets/img/close.png") no-repeat;
  }
  .nav {
    padding-top: 50px;
    text-align: center;
    padding-bottom: 10px;
    a {
      text-decoration: none;
      color: #999;
      &.active {
        color: #000;
      }
    }
  }
  .content {
    width: 355px;
    height: 300px;
    margin: 10px auto 0;
  }
  .phoneLogin {
    .row {
      display: flex;
      margin-bottom: 20px;
      .ipt {
        height: 50px;
        outline: none;
        flex: 1;
        text-indent: 1em;
      }
      .btncode {
        color: #fff;
        background-color: #083490;
        margin-left: 10px;
        width: 84px;
      }
      .btnlogin {
        height: 50px;
        color: #fff;
        background-color: #083490;
        width: 100%;
      }
    }
  }
}
/* 微信二维码样式 */
#weixin {
  /* background-color: #fcf; */
  display: flex;
  justify-content: center;
  margin-top: -20px;
}
/* /deep/深入改动子组件样式 */
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>